import 'package:flutter/material.dart';

import 'tag_flow_widget.dart';

class TagsPage extends StatefulWidget {
  const TagsPage({super.key});

  @override
  State<TagsPage> createState() => _TagsPageState();
}

class _TagsPageState extends State<TagsPage> {
  bool _expanded = false;
  List<int> _visibleIndices = [];
  bool _layoutCalculated = false;

  // 设置默认显示行数
  final int _defaultVisibleRows = 2; // 根据图片，默认显示2行

  // 所有标签数据
  final List<String> _allTags = [
    'All',
    'Action',
    'Adventure',
    'Drama',
    'Magic',
    'Manhwa',
    'Martial Arts',
    'Seinen',
    'Fantasy',
    'Isekai',
    'Reincarnation',
    'Webtoon',
    'Super Power',
    'Romance',
    'Psychological',
    'Shounen',
    'Mature',
    'Mystery',
    'Supernatural',
    'Comedy',
    'Murim',
    'Overpowered',
    'Returner',
    'System',
    'Tragedy',
  ];

  // 其他分组标签
  final List<String> _statusTags = ['All', 'Ongoing', 'Completed'];
  final List<String> _typeTags = ['All', 'Free', 'Paid', 'Vip'];
  final List<String> _chapterTags = ['All', 'Latest', 'Chapters'];

  // 选中状态
  String? _selectedMainTag;
  String _selectedStatus = 'Completed';
  String _selectedType = 'Vip';
  String _selectedChapter = 'Chapters';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff211839),
      appBar: AppBar(
        title: const Text('Genres'),
        backgroundColor: const Color(0xFF2C2C47),
        elevation: 0,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Genres',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 12),

            // 核心：默认显示两行的可扩展标签
            TagFlowWidget(
              items: _allTags,
              maxRows: 2,
              spaceHorizontal: 30,
              selectedTextColor: Colors.pinkAccent,
              unselectedTextColor: Colors.white70,
              spaceVertical: 0,
              itemHeight: 30,
              itemStyle: const TextStyle(height: 1.1),
            ),

            const SizedBox(height: 24),

            // 其他分组标签
            _buildTagGroup(
              title: 'Status',
              tags: _statusTags,
              selectedTag: _selectedStatus,
              onTagSelected: (tag) => setState(() => _selectedStatus = tag),
            ),
            const SizedBox(height: 16),
            _buildTagGroup(
              title: 'Type',
              tags: _typeTags,
              selectedTag: _selectedType,
              onTagSelected: (tag) => setState(() => _selectedType = tag),
            ),
            const SizedBox(height: 16),
            _buildTagGroup(
              title: 'Chapter',
              tags: _chapterTags,
              selectedTag: _selectedChapter,
              onTagSelected: (tag) => setState(() => _selectedChapter = tag),
            ),
          ],
        ),
      ),
    );
  }

  // 构建可扩展的主标签区域
  Widget _buildExpandableTags() {
    return LayoutBuilder(
      builder: (context, constraints) {
        // 计算可见标签
        if (!_layoutCalculated) {
          _calculateVisibleTags(constraints.maxWidth);
          _layoutCalculated = true;
        }

        // 构建要显示的标签列表
        List<Widget> displayWidgets = [];

        // 添加可见标签
        final displayTags = _expanded
            ? _allTags
            : _visibleIndices.map((i) => _allTags[i]).toList();

        for (var tag in displayTags) {
          displayWidgets.add(
            _buildTag(
              tag: tag,
              isSelected: tag == _selectedMainTag,
              onTap: () => setState(() => _selectedMainTag = tag),
            ),
          );
        }

        // 只有在有更多标签需要显示时才显示展开/收起按钮
        if (_visibleIndices.length < _allTags.length || _expanded) {
          displayWidgets.add(_buildExpandCollapseButton());
        }

        return Wrap(spacing: 8.0, runSpacing: 8.0, children: displayWidgets);
      },
    );
  }

  // 计算可见标签
  void _calculateVisibleTags(double maxWidth) {
    if (_expanded) {
      // 展开状态显示所有标签
      _visibleIndices = List.generate(_allTags.length, (index) => index);
      return;
    }

    // 未展开状态，计算能显示的标签数量
    final maxTags = _getMaxTagsForDefaultRows(maxWidth);
    _visibleIndices = List.generate(
      maxTags < _allTags.length ? maxTags : _allTags.length,
      (index) => index,
    );
  }

  // 计算默认行数能显示的最大标签数
  int _getMaxTagsForDefaultRows(double maxWidth) {
    const tagTextStyle = TextStyle(color: Colors.white, fontSize: 14);

    final expandButtonWidth = _estimateTextWidth('Expand', tagTextStyle) + 20;
    List<double> tagWidths = _allTags.map((tag) {
      return _estimateTextWidth(tag, tagTextStyle) + 20;
    }).toList();

    double currentRowWidth = 0;
    int currentRow = 0;
    int maxTags = 0;

    for (int i = 0; i < _allTags.length; i++) {
      final tagWidth = tagWidths[i];
      final spacing = maxTags > 0 ? 8.0 : 0;

      if (currentRowWidth + spacing + tagWidth <= maxWidth) {
        currentRowWidth += spacing + tagWidth;
        maxTags++;
      } else {
        currentRow++;
        if (currentRow >= _defaultVisibleRows) {
          // 检查最后一行是否能放下展开按钮
          if (currentRowWidth + 8 + expandButtonWidth > maxWidth &&
              maxTags > 0) {
            maxTags--; // 为展开按钮留出空间
          }
          break;
        }
        currentRowWidth = tagWidth;
        maxTags++;
      }
    }

    return maxTags;
  }

  // 估算文本宽度
  double _estimateTextWidth(String text, TextStyle style) {
    final textSpan = TextSpan(style: style, text: text);
    final textPainter = TextPainter(
      text: textSpan,
      maxLines: 1,
      textDirection: TextDirection.ltr,
    );
    textPainter.layout();
    return textPainter.width;
  }

  // 构建单个标签
  Widget _buildTag({
    required String tag,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
        // decoration: BoxDecoration(
        //   color: isSelected ? Colors.purpleAccent : Colors.grey[700],
        //   borderRadius: BorderRadius.circular(4),
        // ),
        child: Text(
          tag,
          style: TextStyle(
            color: isSelected ? Colors.purpleAccent : Colors.white,
            fontSize: 14,
          ),
        ),
      ),
    );
  }

  // 构建展开/收起按钮
  Widget _buildExpandCollapseButton() {
    return GestureDetector(
      onTap: () => setState(() {
        _expanded = !_expanded;
        _layoutCalculated = false;
      }),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
        // decoration: BoxDecoration(
        //   color: Colors.grey[700],
        //   borderRadius: BorderRadius.circular(4),
        // ),
        child: Text(
          _expanded ? 'Less' : 'Expand',
          style: const TextStyle(
            color: Colors.white,
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  // 构建标签分组
  Widget _buildTagGroup({
    required String title,
    required List<String> tags,
    required String selectedTag,
    required ValueChanged<String> onTagSelected,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: const TextStyle(
            color: Colors.white70,
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8.0,
          children: tags.map((tag) {
            final isSelected = tag == selectedTag;
            return GestureDetector(
              onTap: () => onTagSelected(tag),
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 10,
                  vertical: 5,
                ),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.purpleAccent : Colors.grey[700],
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  tag,
                  style: const TextStyle(color: Colors.white, fontSize: 14),
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }
}
